package com.fangcang.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyThread {
	
	static final class PrintTask{
		static ReentrantLock lock = new ReentrantLock();
		static Condition a = lock.newCondition();
		static Condition b = lock.newCondition();
		static Condition c = lock.newCondition();
		
		public void execute(String cha) {
			lock.lock();
			try {
				for(int i=0; i<10; i++) {
					System.out.print(cha);
					if("A".equals(cha)) {
						b.signal();
						a.await();
					}else if("B".equals(cha)) {
						c.signal();
						b.await();
					}else if("C".equals(cha)) {
						a.signal();
						c.await();
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}
	}

	public static void main(String[] args) {
		ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 10, 10000, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));
		final PrintTask task = new PrintTask();
		
		tpe.execute(()->{
			task.execute("A");
		});
		tpe.execute(()->{
			task.execute("B");
		});
		tpe.execute(()->{
			task.execute("C");
		});
		
		tpe.shutdown();
	}
}
